﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Mailer.Model.Repositories;
using System.Text.RegularExpressions;
using NHibernate;
using Mailer.Model;
using Mailer.Model.Types;
using System.Collections;
using NHibernate.Criterion;

namespace Mailer.Controllers
{
	[HandleError]
	public class PublicMailController : Controller
	{

		[AcceptVerbs(HttpVerbs.Get)]
		public ActionResult Html(Guid id)
		{
			ActionResult ret = null;

			ISession sess = SessionUtilities.BeginSession();
			if (sess != null)
			{
				Mail mail = sess.Get<Mail>(id);
				if (mail != null)
				{
					Application app = sess.Get<Application>(mail.ApplicationID);

					//	ViewData["userstylesheet"] = app.GetPropertyValue("userstylesheet");
					//	ViewData["userheadhtml"] = app.GetPropertyValue("userheadhtml");
					//	ViewData["usertophtml"] = app.GetPropertyValue("usertophtml");
					//	ViewData["userbottomhtml"] = app.GetPropertyValue("userbottomhtml");

					string body = mail.GetPropertyValue("htmlbody", "").Trim();

					body = mail.PrepareBody(body, null);

					ret = new RawResult(body, "text/html");


					SessionUtilities.EndSession(sess);

				}
			}

			return ret;
		}


		[AcceptVerbs(HttpVerbs.Get)]
		public ActionResult Text(Guid id)
		{
			ActionResult ret = null;

			ISession sess = SessionUtilities.BeginSession();
			if (sess != null)
			{
				Mail mail = sess.Get<Mail>(id);
				if (mail != null)
				{
					Application app = sess.Get<Application>(mail.ApplicationID);

					//	ViewData["userstylesheet"] = app.GetPropertyValue("userstylesheet");
					//	ViewData["userheadhtml"] = app.GetPropertyValue("userheadhtml");
					//	ViewData["usertophtml"] = app.GetPropertyValue("usertophtml");
					//	ViewData["userbottomhtml"] = app.GetPropertyValue("userbottomhtml");

					string body = mail.GetPropertyValue("plaintextbody", "").Trim();

					body = mail.PrepareBody(body, null);

					ret = new RawResult(body, "text/plain");


					SessionUtilities.EndSession(sess);

				}
			}

			return ret;
		}












































		[AcceptVerbs(HttpVerbs.Get)]
		public ActionResult Subscribe(Guid id)
		{
			ISession sess = SessionUtilities.BeginSession();
			if (sess != null)
			{
				Mail mail = sess.Get<Mail>(id);
				if (mail != null)
				{
					Application app = sess.Get<Application>(mail.ApplicationID);
					if (app != null)
					{
						Utilities.ApplyCustomStyling(ViewData, app);
						ViewData["lists"] = sess.CreateCriteria<List>().Add(Expression.Eq("IsPublic", true)).Add(Expression.Eq("ApplicationID", app.ID)).List<List>();
					}
				}


				SessionUtilities.EndSession(sess);

			}
			return base.View();
		}

		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult Subscribe(Guid id, string name, string email, Guid[] lists)
		{
			ActionResult res = null;

			ISession sess = SessionUtilities.BeginSession();
			if (sess != null)
			{
				Mail mail = sess.Get<Mail>(id);
				if (mail != null)
				{
					Application app = sess.Get<Application>(mail.ApplicationID);
					if (app != null)
					{
						Utilities.ApplyCustomStyling(ViewData, app);
						using (ITransaction transaction = sess.BeginTransaction())
						{

							Recipient recip = sess.CreateCriteria<Recipient>().Add(Expression.Eq("Email", email)).Add(Expression.Eq("ApplicationID", app.ID)).UniqueResult<Recipient>();
							if (recip != null)
							{
								recip.UpdatedBy = Guid.Empty;
								recip.UpdatedDate = DateTime.Now;
								recip.State = (int)RecipientState.Verified;

								foreach (Guid list in lists)
								{
									List listobj = sess.Get<List>(list);
									if (!recip.Lists.Contains(listobj))
										recip.Lists.Add(listobj);
								}

								sess.Save(recip);

								if (!string.IsNullOrEmpty(name))
									recip.SetPropertyValue(sess, "displayname", name);
							}
							else
							{
								Recipient newrecip = new Recipient();
								newrecip.ApplicationID = app.ID;

								foreach (Guid list in lists)
								{
									List listobj = sess.Get<List>(list);
									if (!newrecip.Lists.Contains(listobj))
										newrecip.Lists.Add(listobj);
								}

								newrecip.Email = email;
								newrecip.CreatedBy = Guid.Empty;
								newrecip.CreatedDate = DateTime.Now;
								newrecip.UpdatedBy = Guid.Empty;
								newrecip.UpdatedDate = DateTime.Now;
								newrecip.State = (int)RecipientState.Verified;
								sess.Save(newrecip);

								if (!string.IsNullOrEmpty(name))
									newrecip.SetPropertyValue(sess, "displayname", name);
							}

							ViewData["email"] = "";
							ViewData["name"] = "";

							// ModelState.Add(  .AddModelError("_FORM", ErrorCodeToString(createStatus));

							res = RedirectToAction("SubscribeThanks", new { id = id });

							transaction.Commit();
						}
					}
				}


				SessionUtilities.EndSession(sess);

			}

			return RedirectToAction("SubscribeThanks");
		}


		[AcceptVerbs(HttpVerbs.Get)]
		public ActionResult SubscribeThanks(Guid id)
		{
			ISession sess = SessionUtilities.BeginSession();
			if (sess != null)
			{
				Mail mail = sess.Get<Mail>(id);
				if (mail != null)
				{
					Application app = sess.Get<Application>(mail.ApplicationID);
					if (app != null)
					{
						Utilities.ApplyCustomStyling(ViewData, app);
					}
				}


				SessionUtilities.EndSession(sess);

			}
			return base.View();
		}









		[AcceptVerbs(HttpVerbs.Get)]
		public ActionResult Unsubscribe(Guid id)
		{
			ISession sess = SessionUtilities.BeginSession();
			if (sess != null)
			{
				Mail mail = sess.Get<Mail>(id);
				if (mail != null)
				{
					Application app = sess.Get<Application>(mail.ApplicationID);
					if (app != null)
					{
						Utilities.ApplyCustomStyling(ViewData, app);
						ViewData["lists"] = sess.CreateCriteria<List>().Add(Expression.Eq("IsPublic", true)).Add(Expression.Eq("ApplicationID", app.ID)).List<List>();
					}
				}


				SessionUtilities.EndSession(sess);

			}

			return View();
		}

		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult Unsubscribe(Guid id, string email, Guid[] lists)
		{ 
			ISession sess = SessionUtilities.BeginSession();
			if (sess != null)
			{
				Mail mail = sess.Get<Mail>(id);
				if (mail != null)
				{
					Application app = sess.Get<Application>(mail.ApplicationID);
					if (app != null)
					{
						Utilities.ApplyCustomStyling(ViewData, app);

						using (ITransaction transaction = sess.BeginTransaction())
						{
							Recipient recip = sess.CreateCriteria<Recipient>()
								.Add(Expression.Eq("Email", email))
								.Add(Expression.Eq("ApplicationID", app.ID))
								.UniqueResult<Recipient>();

							if (recip != null)
							{
								recip.UpdatedBy = Guid.Empty;
								recip.UpdatedDate = DateTime.Now;
								foreach (Guid g in lists)
								{
									List list = sess.Get<List>(g);
									if (list != null)
										if (recip.Lists.Contains(list))
											recip.Lists.Remove(list);
								}
								sess.Save(recip);
							}

							transaction.Commit();
						}

					}
				}


				SessionUtilities.EndSession(sess);

			}

			return RedirectToAction("UnsubscribeThanks");
		}


		[AcceptVerbs(HttpVerbs.Get)]
		public ActionResult UnsubscribeThanks(Guid id)
		{
			ISession sess = SessionUtilities.BeginSession();
			if (sess != null)
			{
				Mail mail = sess.Get<Mail>(id);
				if (mail != null)
				{
					Application app = sess.Get<Application>(mail.ApplicationID);
					if (app != null)
					{
						Utilities.ApplyCustomStyling(ViewData, app);
					}
				}


				SessionUtilities.EndSession(sess);

			}
			return base.View();
		}




		[ActionName("shim.gif")]
		[AcceptVerbs(HttpVerbs.Get)]
		public ActionResult Shim_Gif(Guid id, Guid? recipient)
		{
			if (recipient.HasValue && recipient.Value != Guid.Empty)
			{
				ISession sess = SessionUtilities.BeginSession();
				if (sess != null)
				{
					Mail mail = sess.Get<Mail>(id);
					if (mail != null)
					{
						//	Application app = sess.Get<Application>(mail.ApplicationID);
						//	if (app != null)
						//	{
						// tagga recipient som verifierad

						Recipient recipobj = sess.Get<Recipient>(recipient.Value);
						if (recipobj != null)
						{
							using (ITransaction trans = sess.BeginTransaction())
							{
								recipobj.State = (int)RecipientState.Verified;
								sess.Save(recipobj);
								trans.Commit();
							}
						}

						// hitta mottagaren + mailet i SendQueuen och markera som läst.

						SendQueue queueitem = sess.CreateQuery("select sq from SendQueue sq where sq.RecipientID = :recipient and sq.MailID = :mail")
							.SetParameter("recipient", recipient.Value)
							.SetParameter("mail", mail.ID)
							.UniqueResult<SendQueue>();
						if (queueitem != null)
						{
							using (ITransaction trans = sess.BeginTransaction())
							{
								queueitem.State = (int)QueueState.Read;
								sess.Save(queueitem);
								trans.Commit();
							}
						}
						//	}

						// tagga mailet som mottaget av mottagaren - senare problem
					}

					SessionUtilities.EndSession(sess);
				}

				Logger.Debug(typeof(PublicMailController), "Mail tracked; mail=" + id + ", recipient=" + recipient);
			}
			else
			{
				Logger.Debug(typeof(PublicMailController), "Mail tracked; mail=" + id + ", unknown recipient");
			}

			byte[] bytes = System.IO.File.ReadAllBytes(Server.MapPath("~/Content/shim.gif"));

			return new RawResult(bytes, "image/gif");
		}



	}
}
